<template>
  <div>
    <div class="top">
      <p>摄像管理</p>
    </div>

    <div class="selects">
      <el-row>
        <el-form ref="form" :model="form" label-width="150px">
          <el-col :span="8">
            <el-form-item label="摄像头名称：">
              <el-input v-model="form.camera_name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="摄像头编码：">
              <el-select v-model="form.camera_no" placeholder="全部" clearable>
                <el-option v-for="(item, index) in cameraSns" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="绑定状态：">
              <el-select v-model="form.bind_status" placeholder="全部" clearable>
                <el-option label="已绑定" value="1"></el-option>
                <el-option label="未绑定" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属机器人：">
              <el-select v-model="form.dog_sn" placeholder="全部">
                <el-option v-for="(item) in robots" :key="item.dog_sn" :label="item.dog_name"
                  :value="item.dog_sn"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间：">
              <el-date-picker v-model="time" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']" @change="changeTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="buttons">
            <el-button @click="reset()">重置</el-button>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-col>
          <el-col :span="24">
            <el-button type="primary" @click="createCamear" icon="el-icon-plus">新增摄像头</el-button>
          </el-col>
        </el-form>
      </el-row>

    </div>

    <el-row>
      <el-table :data="tableData.list" height="460" :highlight-current-row="true" border
        :header-cell-style="{ background: '#f5f5f5' }">
        <el-table-column type="index" label="序号" align="center" width="55">
        </el-table-column>
        <el-table-column prop="camera_name" label="摄像头名称" align="center">
        </el-table-column>
        <el-table-column prop="camera_sn" label="摄像头编码" align="center">
        </el-table-column>
        <el-table-column prop="bindStatusName" label="绑定状态" align="center">
        </el-table-column>
        <el-table-column prop="dog_name" label="所属机器人" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" align="center">
        </el-table-column>

        <el-table-column label="操作" align="center" width="350">

          <template slot-scope="scope">
            <el-popover trigger="manual" popper-class="message-popover" v-model="visiblepop">
              <div class="preview-title">
                <span>视频预览</span>
                <i class="el-icon-close" @click="close"></i>
              </div>
              <div class="preview">
                <video-player @error="videoError" v-if="showVideoFlag" @play="onPlayerPlay($event)"
                  @pause="onPlayerPause($event, 'm')" class="video-player vjs-custom-skin" ref="videoPlayer"
                  :playsinline="true" :options="playerOptions">
                </video-player>
              </div>
              <el-button type="text" slot="reference" @click="openDown(scope.row)">预览</el-button>
            </el-popover>

            <!-- <el-button type="text"
                       @click="preview()" slot="reference">预览</el-button> -->
            <el-button type="text" @click="modify(scope.row)">修改</el-button>
            <el-button type="text" @click="unbinding(scope.row)">解绑</el-button>
            <el-button type="text" @click="bind(scope.row)">绑定</el-button>
            <el-button type="text" @click="del(scope.row)">删除</el-button>

          </template>

        </el-table-column>
      </el-table>
      <div class="footer_custom">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
          :page-sizes="[10, 20, 30, 50, 100]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total_count" background align="center">
        </el-pagination>
      </div>
    </el-row>
    <!-- 添加摄像头 -->
    <el-dialog title="新增摄像头" :visible.sync="dialogVisible" width="30%">

      <el-form ref="editCameraForm" :model="editCameraForm" label-width="100px" :rules="rules">
        <el-form-item label="摄像头名称：" prop="camera_name" label-width='130px'>
          <el-input placeholder="请输入" v-model="editCameraForm.camera_name"></el-input>
        </el-form-item>
        <el-form-item label="摄像头编码：" prop="camera_sn" label-width='130px'>
          <el-input v-model="editCameraForm.camera_sn" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="备注：" label-width='130px'>
          <el-input type="textarea" v-model="editCameraForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCamera">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 绑定摄像头 -->
    <el-dialog title="绑定摄像头" :visible.sync="cameraDialogVisible" append-to-body custom-class="custom_dialog" width="60%">
      <div class="dialog_filter">
        <div class="item">
          <span class="label">机器人名称：</span>
          <el-input v-model="robotDialogFilter.dog_name" placeholder="请输入"></el-input>
        </div>
        <div class="item">
          <span class="label">机器人编号：</span>
          <el-input v-model="robotDialogFilter.dog_sn" placeholder="请输入"></el-input>
        </div>
        <div class="item">
          <el-button type="primary" icon="el-icon-search" @click="getRobotNotBindList">查询</el-button>
        </div>
      </div>
      <div class="table">
        <customer-table :tableInfo="dialogTableInfo" :selection="true"
          @handleSelectionChange="handleSelectionChange"></customer-table>
      </div>
      <el-pagination :page-sizes="[100, 200, 300, 400]" :page-size="100" layout="total, prev, pager, next, jumper"
        :total="dialogTableInfo.total" @current-change="handleDialogCurrentChange">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confrimBindCamera">确 定</el-button>
        <el-button @click="cameraDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import customerTable from "@/pages/Robot/components/CustomerSingleSelectTable.vue";
import customFooter from "@/pages/Robot/components/CustomFooter.vue";
import { RobotApi } from '@/services/PersonalCenter'
import moment from 'moment'
// 引入video样式
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
// 引入hls.js
import 'videojs-contrib-hls.js/src/videojs.hlsjs'

export default {
  name: "Camera",
  components: {
    customerTable,
    customFooter
  },
  props: {
    // videoURL: {
    //   type: String,
    //   default: ''
    // },
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      videoURL: '',
      cameraSns: [],
      robotDialogFilter: {
        dog_sn: '',
        dog_name: '',
        flag: 1,
        is_page: 1,
        page: 1,
        page_size: 10,
      },
      bindCameraid: '',
      dialogTableInfo: {
        column: [
          {
            label: "序号",
            prop: "index",
            type: "index",
            width: "50",
          },
          {
            label: "机器人名称",
            prop: "dog_name",
            width: '200'
          },
          {
            label: "机器人编号",
            prop: "dog_sn",
            width: '200'
          },
          {
            label: "机器人类型",
            prop: "dog_type",
            width: '200'
          },
          {
            label: "机器人型号",
            prop: "dog_model",
            width: '200'
          },
          {
            label: "是否绑定摄像头",
            prop: "state",
            width: '200'
          },
        ],
        data: [],
        total: 0,
      },
      visiblepop: false,
      cameraDialogVisible: false,
      time: [],
      currentPage: 1,
      dialogVisible: false,
      cameraIndexCode: '',
      tableData: {
        list: [],
        page: 1,
        total_count: 1
      },
      form: {
        bind_status: '',
        start_time: '',
        end_time: '',
        camera_name: '',
        camera_no: '',
        dog_sn: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },
      robots: [],
      editCameraForm: {
        camera_name: '',
        camera_sn: '',
        remark: '',
      },
      rules: {
        camera_name: [
          { required: true, message: '请输入摄像头名称', trigger: 'blur' }
        ],
        camera_sn: [
          { required: true, message: '请输入摄像头编码', trigger: 'blur' }
        ]
      },
      bindCameras: [],
      recentVal: 0,//默认为老平台
      showVideoFlag: true,
      playCount: 0,//播放的次数；
      // 判断截屏按钮是否已添加
      screenButton: false,
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'application/x-mpegURL',
            // src: 'http://125.124.108.154:83/openUrl/6ZJlb7q/live.m3u8'
            src: 'http://125.124.108.154:83/openUrl/OHAc9i0/live.m3u8'
          }
        ],

        poster: '', // 你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂时无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          // 全屏按钮
          fullscreenToggle: true
        }
      },
    }
  },
  created() {
    this.getRobotNameBox();
    this.getCameraSnBox();
    this.getList()
  },
  methods: {
    changeTime(val) {
      this.requestParam.start_time = val[0]
      this.requestParam.end_time = val[1]
    },
    getRobotNameBox() {
      RobotApi.getRobotNameBox().then(res => {
        if (res.code == 0) {
          this.robots = res.data.list;
        }
      })
    },
    getCameraSnBox() {
      RobotApi.getCameraSnBox().then(res => {
        if (res.code == 0) {
          this.cameraSns = res.data.list;
        }
      })
    },
    createCamear() {
      this.editCameraForm = {
        camera_name: '',
        camera_sn: '',
        remark: '',
      }
      this.dialogVisible = true
    },
    editCamera() {
      this.$refs.editCameraForm.validate((valid) => {
        if (valid) {
          RobotApi.setCameras({
            data: this.editCameraForm
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('编辑成功')
              this.dialogVisible = false
              this.getList();
              this.getCameraSnBox();
            }
          })
        }
      })
    },
    getList() {
      RobotApi.getCameraList({
        params: this.form
      }).then(res => {
        if (res.code == 0) {
          this.tableData = res.data
          this.tableData.list.map((item) => {
            item.created_at = moment(item.created_at).format('YYYY-MM-DD HH:mm:ss')
            item.bindStatusName = item.bind_status == 1 ? '已绑定' : '未绑定'
          })
        }
      })
    },
    handleSizeChange(page_size) {
      this.form.page_size = page_size
      this.form.page = 1
      this.getList()

    },
    handleCurrentChange(page) {
      this.form.page = page
      this.getList()
    },
    getRobotNotBindList() {
      RobotApi.getRobotNotBindList({
        params: this.robotDialogFilter
      }).then(res => {
        if (res.code == 0) {
          res.data.list.forEach((item) => {
            item.state = '未绑定'
          })
          this.dialogTableInfo.data = res.data.list;
          this.dialogTableInfo.total = Number(res.data.total_count);
        }
      })
    },
    handleDialogCurrentChange(page) {
      this.robotDialogFilter.page = page;
      this.getRobotNotBindList();
    },
    handleSelectionChange(val) {
      this.bindCameras = val;
    },
    confrimBindCamera() {
      if(this.bindCameras.length==0){
        this.$message.error('请选择机器人进行绑定')
        return
      }
      if(this.bindCameras.length>1){
        this.$message.error('只能选择一个机器人进行绑定')
        return
      }
      let dog_sn = this.bindCameras[0].dog_sn;
      RobotApi.operateCamera({
        params: {
          camera_id: this.bindCameraid,
          flag: 1,
          dog_sn:dog_sn
        }
      }).then(res=>{
        if(res.code==0){
          this.$message.success('绑定成功')
          this.cameraDialogVisible = false
          this.getList();
          this.bindCameraid = '';
          this.bindCameras = [];
        }
      })
    },
    close() {
      this.visiblepop = false
    },
    openDown(row) {
      this.videoURL = row.camera_sn;
      this.cameraIndexCode = row.camera_sn;
      this.getPreviewideoUrl();
      this.visiblepop = !this.visiblepop;
    },
    bind(row) {
      this.bindCameraid = row.camera_id;
      this.getRobotNotBindList();
      this.cameraDialogVisible = true
    },
    modify(row) {
      this.editCameraForm = {
        camera_id: row.camera_id,
        camera_name: row.camera_name,
        camera_sn: row.camera_sn,
        remark: row.remark,
      }
      this.dialogVisible = true
    },
    reset() {
      this.form = {
        bind_status: '',
        start_time: '',
        end_time: '',
        camera_name: '',
        camera_no: '',
        dog_sn: '',
        is_page: 1,
        page: 1,
        page_size: 10
      }
      this.time = []
      this.getList();
    },
    del(row) {
      this.$confirm('确定删除此摄像头？', '删除摄像头', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        RobotApi.operateCamera({
          params: {
            camera_id: row.camera_id,
            flag: 3
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.getList()
            this.getCameraSnBox();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    unbinding(row) {
      this.$confirm('确定解除绑定此摄像头？', '解绑摄像头', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        RobotApi.operateCamera({
          params: {
            camera_id: row.camera_id,
            flag: 2
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解绑'
        });
      });
    },

    videoError(e) {
      if (this.videoURL == '') {
        // this.reRender()
      } else {
        this.cameraIndexCode = '';
        this.cameraIndexCode = this.videoURL
        this.getPreviewideoUrl();
      }
    },
    // 获取视频预览数据流
    getPreviewideoUrl() {
      if (this.detail.display === 'none' || this.detail.display === '') return
      this.getVideoReset();
      // 正式https://hikproxy.hibuilding.cn/proxy
      // 开发http://114.215.254.34:9091/proxy
      this.axios
        .post(
          'https://hikproxy.hibuilding.cn/proxy',
          {
            cameraIndexCode: this.cameraIndexCode,
            // cameraIndexCode: this.videoURL,
            // cameraIndexCode: 'bc6676de9a13471d931c18c65cd46a78',//测试-暂时先写死
            streamType: 0,
            protocol: 'hls',
            transmode: 1,
            // expand: 'streamform=ts',
            expand: 'transcode=1&videotype=h264',
            streamform: 'ps'
          },
          {
            headers: {
              userId: 'admin',
              'api-path': '/api/video/v1/cameras/previewURLs',
              key: 'ew2124ewe1333ddd',
              'Content-Type': 'application/json',
              recent: '1'
            }
          }
        )
        .then(res => {
          this.showVideoFlag = true;
          this.playerOptions.sources[0].src = res.data.data.url;
        })
        .catch(error => {
          // console.log(error)
        })
    },
    getVideoReset() {//视频重置 
      if (this.detail.display === 'none' || this.detail.display === '') return
      let autoPlayV = this.playerOptions.autoplay;
      if (autoPlayV == true) {//判断当前是否为自动播放
        this.playerOptions.autoplay = true;//播放
      } else {
        this.playerOptions.autoplay = false;//暂停
      };
      this.playerOptions.sources[0] = {
        src: '',
        type: 'application/x-mpegURL'
      };
    },
    onPlayerPlay(player) {//播放
      this.playCount++;
      this.playerOptions.autoplay = true;
      let url = this.playerOptions.sources[0].src || -1;
      if (url == -1 && this.playCount == 1) {
        // this.setTimeoutFunc();//设置延时器
        this.$message.warning('当前视频暂时无法播放,请检查当前视频的配置或视频的播放源头')
      };
    },
    onPlayerPause(player, typeV) { //暂停
      this.playCount = 0;
      this.playerOptions.autoplay = false;
    },
  }
}
</script>

<style lang="scss" scoped>
.el-input,
.el-select,
.el-date-editor {
  width: 100%;
}

.top {
  padding: 0 20px;
  height: 54px;
  display: flex;
  align-items: center;
  border: 2px solid rgba(230, 230, 230, 0.39);

  p {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
}

.selects {
  margin: 15px 0;
  border-bottom: 2px solid rgba(230, 230, 230, 0.39);
  padding-bottom: 20px;

  .buttons {
    display: flex;
    flex-wrap: nowrap;
    justify-content: flex-end;
  }
}

.preview-title {
  width: 100%;
  height: 50px;
  background-color: rgba(102, 102, 102, 1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  color: #409eff;

  .el-icon-close {
    color: #7f7f7f;
    font-size: 20px;
  }
}

.preview {
  width: 861px;
  height: 483px;
}

/deep/ .el-dialog__header {
  text-align: center;
  flex: 1;
  height: 60px;
  line-height: 30px;
  background: #1890ff;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #ffffff;
}

/deep/ .el-dialog__close {
  color: #ffffff;
}

/deep/ .el-dialog__footer {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  padding: 0px 20px 20px;
}

/deep/ .el-row {
  padding: 0 20px;
}

/deep/ .el-dialog__body {
  padding: 30px 20px 20px 20px;
}
</style>
<style lang="scss">
.custom_dialog {
  .el-dialog__header {
    padding: 18px;
    text-align: center;
    background-color: #1890ff;

    .el-dialog__close,
    .el-dialog__title {
      color: white;
      font-weight: bold;
      font-size: 18px;
    }
  }

  .dialog_filter {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .item {
      display: flex;
      align-items: center;
      width: 33%;

      .label {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
        width: 100px;
        text-align: end;
      }

      .el-input {
        flex: 1;
      }

      .el-button {
        margin-left: 50px;
      }
    }
  }

  .table {
    padding-top: 30px;
  }

  .el-dialog__footer {
    text-align: center;
    // padding: 20px 0;

    .el-button--primary {
      margin-left: 50px;
    }
  }
}

.message-popover {
  padding: 0 !important;
  position: fixed !important;
  top: 50% !important;
  left: 54% !important;
  transform: translate(-50%, -50%) !important;

  .popper__arrow {
    display: none !important;
  }
}
</style>